﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using AutoMapper;

namespace MvcApplication2.Models
{
    public static class ModelHelper
    {
        public static UserProfile GetUser(MvcApplication2Context context = null, Guid userGuid = default(Guid), string username = null)
        {
            try
            {


                if (userGuid == default(Guid))
                {
                    var o = Membership.GetUser();
                    if (o != null && o.ProviderUserKey != null)
                    {
                        userGuid = (Guid)o.ProviderUserKey;
                        username = o.UserName;
                    }
                }

                if (userGuid == default(Guid))
                {
                    throw new Exception("GetUser");
                }

                if (context == null)
                    context = new MvcApplication2Context();

                var t = context.UsersProfiles.SingleOrDefault(p => p.MembershipGuid == userGuid);

                if (t == null)
                {
                    t = new UserProfile()
                            {
                                MembershipGuid = userGuid,
                                DisplayName = username,
                            };

                    context.UsersProfiles.Add(t);

                    context.SaveChanges();
                }

                if (String.IsNullOrWhiteSpace(t.DisplayName))
                {
                    t.DisplayName = username;
                    context.SaveChanges();
                }

                return t;
            }
            catch (Exception exception)
            {

                return null;
            }
        }


        internal static ICollection<T2> GetListViewModel<T1, T2>(IEnumerable<T1> modellist)
        {
            Mapper.CreateMap<T1, T2>();

            return modellist.Select(Mapper.Map<T1, T2>).ToList();
        }

        internal static T2 CopyTo<T1, T2>(T1 ex)
        {
            Mapper.CreateMap<T1, T2>();

            return Mapper.Map<T1, T2>(ex);
        }
    }
}